/**
 * The Package Vehicle Controller contains the navigation controls for Moving, Purchasing, Selling,Setting Rate and Viewing Vehicles
 */
package vehicleController;

//import java.awt.Label;
import java.net.URL;
import java.sql.Date;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.ResourceBundle;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.paint.Color;

import org.apache.commons.lang3.StringUtils;

import userController.Navigator;
import validator.Validator;
import vehicleEntity.SaleVehicleEntity;
import vehicleEntity.VehicleDisplayable;
import vehicleLogic.SaleLogic;

/**
 * This class is used for SuperRent Manager to fetch the vehicles which are available for sale and also allows to search and edit the available information
 * @author Arimarajan Parasuraman
 *
 */
public class SellVehicleController implements Initializable{



	@FXML
	private TableColumn<VehicleDisplayable,Integer> vehicleID;

	@FXML
	private TableColumn<VehicleDisplayable,Integer> RegNo;

	@FXML
	private TableColumn<VehicleDisplayable,Integer> VIN;

	@FXML
	private TableColumn<VehicleDisplayable,String> vehicleType;

	@FXML
	private TableColumn<VehicleDisplayable,String> vehicleClass;

	@FXML
	private TableColumn<VehicleDisplayable,String> vehicleName;

	@FXML
	private TableColumn<VehicleDisplayable, Date> movedOn;

	@FXML
	private TableColumn<VehicleDisplayable, Double> saleAmount;

	@FXML
	private TableView<VehicleDisplayable> saleList; //sale list is the fxml table name

	@FXML
	private TextField SearchField;

	@FXML
	private TextField SearchField2; //fx:id

	@FXML
	private Label RegNoField;

	@FXML
	private Label VINField;

	@FXML
	private Label vehicleTypeField;

	@FXML
	private Label vehicleClassField;

	@FXML
	private Label vehicleNameField;

	@FXML
	private TextField movedOnField;

	@FXML
	private TextField saleAmountField;

	@FXML
	private Label VehicleName2;

	@FXML
	private Label VehicleClass2;

	@FXML
	private Label VehicleType2;

	@FXML
	private Label SaleAmount2;

	@FXML
	private TextField SoldAmount2;

	@FXML
	private TextField SoldTo2;

	@FXML
	private Label message;

	@FXML
	private Button sellVehicle_fxid;
	//table.setEditable(true);
	private static ObservableList<VehicleDisplayable> list;
	private static SaleVehicleEntity saleVehicleEntity;
	private static int vId;
	private static int sceneNo =0;
	private static VehicleDisplayable vd;


	/**
	 * This method loads the vehicle sale list FXML file as a table with values. 
	 * @param void 
	 * @Pre Retrieves fxids from FXML file 
	 * @Post Get Values for the fxids
	 * @return none
	 */
	public void fetchSaleVehicles(){
		SaleLogic sl = new SaleLogic();
		list=FXCollections.observableArrayList();
		try {
			list=sl.fetchSaleVehicle();
			Navigator.setInitailize(true);
			sceneNo =1;
			Navigator.loadStackPane(Navigator.VEHICLESALELISTFXML); 
			list = null;
		} catch (Exception e) {
			e.printStackTrace();	
			Navigator.loadStackPane(Navigator.EXCEPTIONINFOFXML);
		}

	}

	/**
	 * This method is to call back the fetchSaleVehicles method by creating an object for SellVehicleController
	 * @param void
	 * @Pre Current form will loaded
	 * @Post Previous form will be loaded
	 * @return none
	 */
	//for Back button
	@FXML
	public void sell_edit(){
		System.out.println("sale list invoked from Sell Vehicle Controller from Edit ");
		SellVehicleController sellController = new SellVehicleController();
		sellController.fetchSaleVehicles();
	}

	/**
	 * This methods loads the vehicle id search box
	 * @param event 
	 * @Pre All Items related to sale will be retrieved
	 * @Post only entered search vehicle id details will be displayed
	 * @return none
	 */
	//calling Scene2 search box for editSQ
	@FXML
	public void editSale(ActionEvent event){
		// load search frame
		System.out.println("Scene 2 --> sale search list invoked");	
		sceneNo = 2;
		ObservableList<VehicleDisplayable> selection = saleList.getSelectionModel().getSelectedItems();
		if(selection.size()>0)
		{
			
			vd = selection.get(0);
			System.out.println("vd vehivle id"+ vd.getVehicleID());
			SaleLogic salelogic = new SaleLogic();
			try
			{
				saleVehicleEntity = salelogic.fetchSaleVehicleDetail_for_edit(vd.getVehicleID());
				vId = vd.getVehicleID();
				System.out.println();
				sceneNo = 3;
				Navigator.loadStackPane(Navigator.VEHICLETEXTFORMFXML);
				return;
				
			}
			catch (SQLException e)
			{
				e.printStackTrace();
			}
						
		}
		saleVehicleEntity = null;
		vd = null;
		Navigator.loadStackPane(Navigator.VEHICLESALESEARCHFXML); 
	}

	/**
	 * This method loads Editable text form 
	 * @param event
	 * @Pre Data values are fetched and place in the text form for the search vehicle Id which is given in the search field. 
	 * @Post Edited data will be updated in the database tables
	 * @throws SQLException
	 * @return none
	 */
	//calling Scene3 Edit Text Form
	@FXML
	public void searchSaleVehicle(ActionEvent event){
		// validate vehicleID

		System.out.println("Scene3 --> search vehicle ID : " + SearchField.getText());
		if(SearchField.getText() != null && !StringUtils.isEmpty(SearchField.getText())){
			if(Validator.validateStringContainsInteger(SearchField.getText())){
				vId = Integer.parseInt(SearchField.getText());						//getting VehicleId from search box
				SaleLogic saleLogic = new SaleLogic();
				saleVehicleEntity = new SaleVehicleEntity();
				try {
					saleVehicleEntity = saleLogic.fetchSaleVehicleDetail_for_edit(vId);
					if(saleVehicleEntity != null){
						sceneNo = 3;
						Navigator.setInitailize(true);
						Navigator.loadStackPane(Navigator.VEHICLETEXTFORMFXML); 
						saleVehicleEntity = null;
					}
					else{
						message.setText("Value for given vehicle ID not found");
					}
				} catch (SQLException e) {
					message.setText("DB Exception occured please try again later");
					e.printStackTrace();
				}
			}
			else{
				message.setText("Please enter Valid vehicle ID");
			}
		}
		else{
			message.setText("Please enter the vehicle ID");
		}

	}

	/**
	 * This method loads the save edit information
	 * @param event 
	 * @Pre once the user searched a specific vehicle and presses sell button
	 * @Post The searched vehicle Id sale list is updated in the respective tables
	 * @throws SQLException
	 * @return none
	 */
	// calling Scene4 Save Edit Information
	@FXML
	public void saveUpdatedValue_for_edit(ActionEvent event){

		if(RegNoField.getText() != null && !StringUtils.isEmpty(RegNoField.getText())){
			if(VINField.getText() != null && !StringUtils.isEmpty(VINField.getText())){
				if(vehicleTypeField.getText() != null && !StringUtils.isEmpty(vehicleTypeField.getText())){
					if(vehicleClassField.getText() != null && !StringUtils.isEmpty(vehicleClassField.getText())){
						if(vehicleNameField.getText() != null && !StringUtils.isEmpty(vehicleNameField.getText())){
							if(saleAmountField.getText() != null && !StringUtils.isEmpty(saleAmountField.getText())){
								if(Validator.validateStringContainsDouble(saleAmountField.getText())){
								SaleLogic salesave = new SaleLogic();
								saleVehicleEntity = new SaleVehicleEntity();
								saleVehicleEntity.setRegNo(RegNoField.getText());
								saleVehicleEntity.setVin(VINField.getText());
								saleVehicleEntity.setVehicleType(vehicleTypeField.getText());
								saleVehicleEntity.setVehicleClass(vehicleClassField.getText()); //CCCCCCCCCChangedddd
								//System.out.println("getter : "+saleVehicleEntity.getVehicleClass());
								saleVehicleEntity.setVehicleName(vehicleNameField.getText());
								saleVehicleEntity.setVehicleId(vId);
								saleVehicleEntity.setSaleAmount(new Double(saleAmountField.getText()));
								try {
									System.out.println("in scene 7 , ");
									salesave.saveUpdated_for_edit(saleVehicleEntity);
									message.setTextFill(Color.GREEN);
									message.setText("Vehicle successfully updated");
								} catch (SQLException e) {
									e.printStackTrace();
									message.setText("DB exception occurred. Please try again ");
								}
								}
								else{
									message.setText("Sale Amount is invalid ");
								}
							}
							else{
								message.setText("Sale Amount is required ");
							}
						}
						else{
							message.setText("Vehicle Name is required ");
						}
					}
					else{
						message.setText("Vehicle Class is required ");
					}
				}
				else{
					message.setText("Vehicle Type is required ");
				}
			}
			else{
				message.setText("VIN No is required");
			}
		}
		else{
			message.setText("Reg No is required");
		}


	}

	/**
	 * Search window for searching a vehicle based on the vehicle id will be loaded
	 * @param event
	 * @Pre User when logged in as manager and clicks the Sell button action
	 * @Post Sale list editable form will be displayed
	 * @return none
	 * 
	 */
	//calling Scene5 Sell Search
	@FXML
	public void saleVehicle(ActionEvent event) {
		// load search frame
		System.out.println("Loading Scene 5 Sell Search ... ");
		sceneNo = 5;
		//-------------------------------------------------------------------------------------
		ObservableList<VehicleDisplayable> selection = saleList.getSelectionModel().getSelectedItems();
		if(selection.size()>0)
		{
			
			vd = selection.get(0);
			System.out.println("vd vehivle id"+ vd.getVehicleID());
			SaleLogic salelogic = new SaleLogic();
			try
			{
				saleVehicleEntity = salelogic.fetchSaleVehicleDetail_for_sale(vd.getVehicleID());
				vId = vd.getVehicleID();
				System.out.println();
				sceneNo = 6;
				Navigator.loadStackPane(Navigator.VEHICLEEDITABLEFORMFXML);
				return;
				
			}
			catch (SQLException e)
			{
				e.printStackTrace();
			}
						
		}
		saleVehicleEntity = null;
		vd = null;
		//--------------------------------------------------------------------------------------
		Navigator.loadStackPane(Navigator.VEHICLESELLSEARCHFXML); 
	}

	/**
	 * Editable form with details of the searched vehicle is loaded in this method
	 * @param event
	 * @Pre Vehicle Id is passed in order to search a vehicle
	 * @Post The Edited details are updated in the successfully and Vehicle Id is passed to Sale logic
	 * @throws SQLException
	 * @return none
	 */
	//calling Scene6 Editable Form
	@FXML
	public void sellVehicle(ActionEvent event){

		//vId = Integer.parseInt(SearchField.getText());
		System.out.println("Loading Scene 6 Editable Form ... ");
		if(SearchField2.getText() != null && !StringUtils.isEmpty(SearchField2.getText())){
			if(Validator.validateStringContainsInteger(SearchField2.getText())){
				vId = Integer.parseInt(SearchField2.getText());
				SaleLogic saleLogic = new SaleLogic();
				saleVehicleEntity = new SaleVehicleEntity();
				try {
					saleVehicleEntity = saleLogic.fetchSaleVehicleDetail_for_sale(vId);
					if(saleVehicleEntity != null){
						System.out.println("sale veh entity null ? "+saleVehicleEntity == null);
						sceneNo = 6;
						Navigator.loadStackPane(Navigator.VEHICLEEDITABLEFORMFXML); //calling 2nd editable form 
						saleVehicleEntity = null;
					}
					else{
						message.setText("Value for given vehicle ID not found");
					}
				} catch (SQLException e) {
					e.printStackTrace();
					message.setText("DB Exception occured please try again later");
				}
			}
			else{
				message.setText("Please enter a Valid Vehicle Id");
			}
		}
		else{
			message.setText("Please enter a Vehicle Id");
		}

	}

	/**
	 * This method updates the edited data values in the editable sale list form for manager
	 * @param event
	 * @Pre   The editable text form contains the values fetched from the database
	 * @Post Updated values will be sent to service method and then updates the tables in database
	 * @throws SQLException
	 * @return none
	 */
 
	//calling scene7 sell update display info
	@FXML
	public void saveUpdatedValue_for_sale(ActionEvent event){
		System.out.println("Saving updated value for Sell");

		SaleLogic salesave = new SaleLogic();
		saleVehicleEntity = new SaleVehicleEntity();
		System.out.println("saveUpdatedValue_for_sale vId "+vId);
		saleVehicleEntity.setVehicleId(vId);
		if(SoldAmount2.getText() != null && !StringUtils.isEmpty(SoldAmount2.getText())){
			if(SoldTo2.getText() != null && !StringUtils.isEmpty(SoldTo2.getText())){
				if(Validator.validateStringContainsDouble(SoldAmount2.getText())){
					saleVehicleEntity.setSoldAmount(new Double(SoldAmount2.getText()));
					saleVehicleEntity.setSoldTo(SoldTo2.getText());
					Calendar cal = Calendar.getInstance();
					saleVehicleEntity.setSoldDate(cal.getTime());
					try {
						System.out.println( SoldAmount2.getText());
						SoldAmount2.setEditable(false);
						SoldTo2.setEditable(false);
						sellVehicle_fxid.setDisable(true);
						sellVehicle_fxid.setVisible(false);
						salesave.saveUpdated_for_sell(saleVehicleEntity);
						message.setText("Vehicle Sold Successfully");
						message.setTextFill(Color.GREEN);
					} catch (SQLException e) {
						e.printStackTrace();
						message.setText("DB Exception occured please try again");
					}

				}
				else{
					message.setText("please enter a valid amount");
				}
			}
			else{
				message.setText("please enter soldTo value");
			}
		}
		else{
			message.setText("Please enter SoldAmount value");
		}

	}

	/**
	 * This method is used to set the values for the cells in the FXML file table
	 * @param arg0 
	 * @param arg1
	 * @Pre Data values retrieved from service
	 * @Post Data values set to the table cells
	 * @return none
	 */
	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {
		// TODO Auto-generated method stub
		//Try fitting a number here so that you don't have to stretch the column on execution... ok calling
		if(Navigator.isInitailize() && list != null && sceneNo ==1){
			//vehicleClass.setMinWidth(10);
			vehicleID.setCellValueFactory(new PropertyValueFactory<VehicleDisplayable,Integer>("vehicleID"));
			RegNo.setCellValueFactory(new PropertyValueFactory<VehicleDisplayable,Integer>("RegNo"));
			VIN.setCellValueFactory(new PropertyValueFactory<VehicleDisplayable,Integer>("VIN"));
			vehicleType.setCellValueFactory(new PropertyValueFactory<VehicleDisplayable,String>("vehicleType"));
			vehicleClass.setCellValueFactory(new PropertyValueFactory<VehicleDisplayable,String>("vehicleClass"));
			vehicleName.setCellValueFactory(new PropertyValueFactory<VehicleDisplayable,String>("vehicleName"));
			movedOn.setCellValueFactory(new PropertyValueFactory<VehicleDisplayable,Date>("movedOn"));
			saleAmount.setCellValueFactory(new PropertyValueFactory<VehicleDisplayable,Double>("saleAmount"));

			saleList.setItems(list);
			Navigator.setInitailize(false);
			sceneNo =0;
		}
		if(sceneNo == 5){
			if(vd !=null)
			{
				SearchField2.setText(vd.getVehicleID()+"");
			}
			else
			{
				SearchField2.setText(""); //				
			}
			Validator.addTextLimiter(SearchField2, 6);
			sceneNo =0;
		}
		if(sceneNo == 2){
			if(vd !=null)
			{
				SearchField.setText(vd.getVehicleID()+"");
			}
			else
			{
				SearchField.setText("");
				
			}
			Validator.addTextLimiter(SearchField, 6);
			sceneNo =0;
		}//Navigator.isInitailize() && 
		
		if(saleVehicleEntity != null && sceneNo == 3){
			RegNoField.setText(saleVehicleEntity.getRegNo());
			VINField.setText(saleVehicleEntity.getVin());
			vehicleTypeField.setText(saleVehicleEntity.getVehicleType());
			vehicleClassField.setText(saleVehicleEntity.getVehicleClass());
			vehicleNameField.setText(saleVehicleEntity.getVehicleName());
			saleAmountField.setText(new Double(saleVehicleEntity.getSaleAmount()).toString());
		//	Validator.addTextLimiter(RegNoField, 8);
		//	Validator.addTextLimiter(VINField, 15);
		//	Validator.addTextLimiter(vehicleTypeField, 15);
		//	Validator.addTextLimiter(vehicleClassField, 5);
			//Validator.addTextLimiter(movedOnField, 7);
			Validator.addTextLimiter(saleAmountField, 7);
			sceneNo = 0;
			Navigator.setInitailize(false);
		}else{
			System.out.println("in else , "+Navigator.isInitailize() + (saleVehicleEntity!=null)+ sceneNo);
		}
		if(!Navigator.isInitailize() && saleVehicleEntity != null && sceneNo == 6){
			VehicleType2.setText(saleVehicleEntity.getVehicleType());
			VehicleClass2.setText(saleVehicleEntity.getVehicleClass());
			VehicleName2.setText(saleVehicleEntity.getVehicleName());			
			SaleAmount2.setText(new Double(saleVehicleEntity.getSaleAmount()).toString());
			Validator.addTextLimiter(SoldAmount2, 7);
			Validator.validateStringContainsDouble(SoldAmount2.getText());
			Validator.addTextLimiter(SoldTo2, 30);
			sceneNo =0;

		}
		


	}



}
